package main

import (
	"fmt"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/cache"
	v1 "k8s.io/api/core/v1"
	"k8s.io/klog/v2"
	"os"
	"os/exec"
	"path"
)

const (
	hostRoot    = "/host"                  // 挂载的主机根目录
	podBasePath = "/var/lib/kubelet/pods/" // Kubernetes Pod 存储基础路径
)

func main() {
	// 创建 Kubernetes 客户端
	config, err := rest.InClusterConfig()
	if err != nil {
		klog.Fatalf("Error creating in-cluster config: %v", err)
	}

	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		klog.Fatalf("Error creating clientset: %v", err)
	}

	// 创建 SharedInformerFactory
	factory := informers.NewSharedInformerFactoryWithOptions(
		clientset,
		0,
		informers.WithNamespace(""), // 监听所有命名空间
	)

	podInformer := factory.Core().V1().Pods().Informer()

	// 注册事件处理函数
	podInformer.AddEventHandler(&cache.ResourceEventHandlerFuncs{
		DeleteFunc: func(obj interface{}) {
			pod := obj.(*v1.Pod)
			cleanPodDirs(pod)
		},
	})

	// 启动 Informer
	stopCh := make(chan struct{})
	defer close(stopCh)
	factory.Start(stopCh)
	factory.WaitForCacheSync(stopCh)

	// 保持运行
	select {}
}

func cleanPodDirs(pod *v1.Pod) {
	podUID := string(pod.UID)
	klog.Infof("Cleaning directories for deleted pod: %s/%s", pod.Namespace, pod.Name)

	// 清理标准 Pod 目录
	podPath := path.Join(hostRoot, podBasePath, podUID)
	if err := removePath(podPath); err != nil {
		klog.Errorf("Error removing pod directory %s: %v", podPath, err)
	}

	// 这里可以添加其他需要清理的自定义目录
	// 例如：cleanCustomVolumes(pod)
}

func removePath(path string) error {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return nil
	}

	// 使用 nsenter 进入主机命名空间执行删除操作（因为容器在单独 mount namespace 中）
	cmd := exec.Command("nsenter", "--mount=/proc/1/ns/mnt", "rm", "-rf", path)
	output, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("failed to delete path: %s, output: %s, error: %v", path, string(output), err)
	}
	return nil
}
